using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using _10GrpcServer.Services;
using Microsoft.AspNetCore.Authentication.Certificate;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Https;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc(x => { x.EnableDetailedErrors = true; });
builder.WebHost.ConfigureKestrel(o =>
{
	o.ListenAnyIP(5000, listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; });

	// o.ListenAnyIP(5001, listenOptions =>
	// {
	// 	listenOptions.Protocols = HttpProtocols.Http2;
	// 	listenOptions.UseHttps(X509CertificateLoader.LoadPkcs12FromFile("Certs/hardstyle.pfx", "pass1234"));
	// });

	o.ListenAnyIP(5005, listenOptions =>
	{
		listenOptions.UseHttps(httpsOptions =>
		{
			// var localhostCert = CertificateLoader.LoadFromStoreCert(
			// 	"hardstyle", "My", StoreLocation.CurrentUser,
			// 	allowInvalid: true);
			var localhostCert = X509CertificateLoader.LoadPkcs12FromFile("Certs/hardstyle.pfx", "pass1234");
			// var exampleCert = CertificateLoader.LoadFromStoreCert(
			// 	"example.com", "My", StoreLocation.CurrentUser,
			// 	allowInvalid: true);

			listenOptions.UseHttps(new TlsHandshakeCallbackOptions
			{
				OnConnection = context =>
				{
					if (string.Equals(context.ClientHelloInfo.ServerName, "localhost",
						    StringComparison.OrdinalIgnoreCase))
					{
						// Different TLS requirements for this host
						context.AllowDelayedClientCertificateNegotation = true;

						return new ValueTask<SslServerAuthenticationOptions>(
							new SslServerAuthenticationOptions
							{
								ServerCertificate = localhostCert
							});
					}

					return new ValueTask<SslServerAuthenticationOptions>(
						new SslServerAuthenticationOptions
						{
							ServerCertificate = localhostCert
						});
				}
			});
		});
	});
});

var app = builder.Build();
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");

app.Run();
